package cn.iocoder.yudao.module.system.util.a_gaojian;


import okhttp3.*;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
 * @author lxj
 * 视频
 */
public class VideoUtils {
    public static final String VIDEO_3GP = "video/3gpp";
    public static final String VIDEO_AVI = "video/x-msvideo";
    public static final String VIDEO_FLV = "video/x-flv";
    public static final String VIDEO_F4V = "video/x-f4v";
    public static final String VIDEO_GIF = "image/gif";
    public static final String VIDEO_M3U8 = "application/vnd.apple.mpegurl";
    public static final String VIDEO_M4V = "video/x-m4v";
    public static final String VIDEO_MKV = "video/x-matroska";
    public static final String VIDEO_MP4 = "video/mp4";
    public static final String VIDEO_MPEG = "video/mpeg";
    public static final String VIDEO_RM = "application/vnd.rn-realmedia";
    public static final String VIDEO_RMVB = "application/vnd.rn-realmedia-vbr";
    public static final String VIDEO_TS = "video/mp2t";
    public static final String VIDEO_WMV = "video/x-ms-wmv";

    public static final String[] DEFAULT_ALLOWED_EXTENSION = {
            "3gp", "avi", "flv", "f4v", "gif", "m3u8", "m4v", "mkv", "mp4", "mpeg", "rm", "rmvb", "ts", "wmv"
    };
    /**
     * 视频文件名最大长度
     */
    public static final int VIDEO_FILE_NAME_LENGTH_MAX = 80;
    /**
     * 视频文件大小最大限制 1MB
     */
    public static final long VIDEO_FILE_SIZE_MAX = 100 * 1024 * 1024;


    /**
     * 视频上传
     *
     * @param baseDir   相对应用的基目录
     * @param imageFile 视频文件
     * @return 视频文件名称
     */
    public static String upload(String baseDir, MultipartFile imageFile) throws IOException {
        return upload(baseDir, imageFile, DEFAULT_ALLOWED_EXTENSION);
    }

    /**
     * 视频上传
     *
     * @param baseDir       相对应用的基目录
     * @param bufferedImage 视频
     * @return 视频文件名称
     */
    public static String upload(String baseDir, BufferedImage bufferedImage) throws IOException {
        String imageFileName = DateUtils.datePath() + "/" + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
        File desc = getAbsoluteFile(baseDir, imageFileName);
        ImageIO.write(bufferedImage, "jpg", desc);
        String pathFileName = getPathFileName(imageFileName);
        return pathFileName;
    }

    /**
     * 视频上传
     *
     * @param baseDir          相对应用的基目录
     * @param imageFile        视频文件
     * @param allowedExtension 允许上传视频文件类型
     * @return 视频文件名称
     */
    public static String upload(String baseDir, MultipartFile imageFile, String[] allowedExtension) throws IOException {
        //int imageFileNameLength = imageFile.getOriginalFilename().length();
        //if (imageFileNameLength > VIDEO_FILE_NAME_LENGTH_MAX) {
        //throw new ServiceException(ApiResponseCodeEnum.FAIL, "视频文件名过长，最大长度为80字符");
        //error(200, "视频文件名过长，最大长度为80字符");
        //}

        //long size = imageFile.getSize();
        //if (VIDEO_FILE_SIZE_MAX > 0 && size > VIDEO_FILE_SIZE_MAX) {
        //  throw new ServiceException(ApiResponseCodeEnum.FAIL, "视频文件过大，最大限制为1MB");
        //error(200, "视频文件过大，最大限制为1MB");
        //}

        // 校验
        if (!assertAllowed(imageFile, allowedExtension)) {
            error(200, "视频文件格式错误，允许上传3gp,avi,flv,f4v,gif,m3u8,m4v,mkv,mp4,mpeg,rm,rmvb,ts,wmv格式");
        }

        String imageFileName = extractFilename(imageFile);

        //原本逻辑---直接上传
        //File desc = getAbsoluteFile(baseDir, imageFileName);
        //imageFile.transferTo(desc);

        //切片上传
        FileUtils.splitFile(baseDir,imageFile,imageFileName);
        String pathFileName = getPathFileName(imageFileName);

        return pathFileName;
    }

    /**
     * 校验
     *
     * @param imageFile        视频文件
     * @param allowedExtension 允许上传视频文件类型
     */
    public static Boolean assertAllowed(MultipartFile imageFile, String[] allowedExtension) {
        String extension = getExtension(imageFile);
        //  throw new ServiceException(ApiResponseCodeEnum.FAIL, "视频文件格式错误，允许上传jpg,jpeg,png,gif,bmp格式");
        return isAllowedExtension(extension, allowedExtension);
    }

    /**
     * 获取视频文件名称的后缀
     *
     * @param imageFile 视频文件
     * @return 后缀
     */
    public static String getExtension(MultipartFile imageFile) {
        String extension = FilenameUtils.getExtension(imageFile.getOriginalFilename());
        if (StringUtils.isBlank(extension)) {
            extension = getExtension(imageFile.getContentType());
        }
        return extension;
    }

    public static String getExtension(String prefix) {
        switch (prefix) {
            case VIDEO_3GP:
                return "3gp";
            case VIDEO_AVI:
                return "avi";
            case VIDEO_FLV:
                return "flv";
            case VIDEO_F4V:
                return "f4v";
            case VIDEO_GIF:
                return "gif";
            case VIDEO_M3U8:
                return "m3u8";
            case VIDEO_M4V:
                return "m4v";
            case VIDEO_MKV:
                return "mkv";
            case VIDEO_MP4:
                return "mp4";
            case VIDEO_MPEG:
                return "mpeg";
            case VIDEO_RM:
                return "rm";
            case VIDEO_RMVB:
                return "rmvb";
            case VIDEO_TS:
                return "ts";
            case VIDEO_WMV:
                return "wmv";
            default:
                return "";
        }
    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension        上传视频文件类型
     * @param allowedExtension 允许上传视频文件类型
     * @return true/false
     */
    public static boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 编码文件名
     */
    public static String extractFilename(MultipartFile imageFile) {
        String extension = getExtension(imageFile);
        //String imageFileName = DateUtils.datePath() + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "." + extension;
        String imageFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + extension;
        return imageFileName;
    }

    public static File getAbsoluteFile(String uploadDir, String imageFileName) {
        File desc = new File(uploadDir + File.separator + imageFileName);
        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
    }

    private static String getPathFileName(String imageFileName) {
        String pathFileName = "/" + imageFileName;
        return pathFileName;
    }







    private static final int CHUNK_SIZE = 1024 * 1024; // 切片大小为1MB

    public static void main(String[] args) {
        String videoFilePath = "/ceshi/94725b215845bc4bcb9cb3c23385589e.mp4";
        String uploadUrl = "http://example.com/upload";

        try {
            List<byte[]> chunks = splitVideoIntoChunks(videoFilePath);
            uploadChunks(chunks, uploadUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static List<byte[]> splitVideoIntoChunks(String videoFilePath) throws IOException {
        List<byte[]> chunks = new ArrayList<>();

        File videoFile = new File(videoFilePath);
        try (InputStream inputStream = new FileInputStream(videoFile)) {
            byte[] buffer = new byte[CHUNK_SIZE];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byte[] chunk = new byte[bytesRead];
                System.arraycopy(buffer, 0, chunk, 0, bytesRead);
                chunks.add(chunk);
            }
        }

        return chunks;
    }

    private static void uploadChunks(List<byte[]> chunks, String uploadUrl) {
        /*for (byte[] chunk : chunks) {
            //将切片上传到指定的上传URL
            //这里可以使用网络请求库，如OkHttp或HttpClient来实现上传操作
            try {
                OkHttpClient client = new OkHttpClient();
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), chunk);
                Request request = new Request.Builder()
                        .url(uploadUrl)
                        .post(requestBody)
                        .build();
                Response response = null;
                response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    System.out.println("切片上传成功");
                } else {
                    System.out.println("切片上传失败");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    }

}
